//
//  NetworkingTool.m
//  BaseFrameworkOC
//
//  Created by Vicent on 2021/9/6.
//

#import "NetworkingTool.h"
#import <AFNetworking/AFNetworking.h>
#import "NSString+Helper.h"

NSInteger const kBFNetworkingTimeoutInterval = 60;

@implementation NetworkingTool

static AFHTTPSessionManager *sessionManager;

NSString *baseUrlPath = @"http://localhost:8080";
NSString *basePicPath = @"";
NSString *baseH5Path = @"";

// 获取baseURL
+ (NSString *)baseUrl {
    NSString *apiUrl = [NSURL URLWithString:baseUrlPath].absoluteString;
    return apiUrl;
}

//中文路径encoding
+ (NSString *)encodingURLWithString:(NSString *)path {
    return [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}

/*
 *  @brief 获取完整路径
 *
 *  @param path 相对路径
 *
 */
+ (NSString *)absoluteUrlWithPath:(NSString *)path {
    if ([NSString isBlankString:path]) {
        return @"";
    }
    if ([NSString isBlankString:[self baseUrl]]) {
        return path;
    }
    NSString *absoluteUrl = path;
    if (![path hasPrefix:@"http://"] && ![path hasPrefix:@"https://"]) {
        if ([path hasPrefix:@"/"]) {
            absoluteUrl = [NSString stringWithFormat:@"%@%@",[self baseUrl], path];
        }else {
            absoluteUrl = [NSString stringWithFormat:@"%@/%@",[self baseUrl], path];
        }
    }
    return absoluteUrl;
}


+ (AFHTTPSessionManager *)sharedAFManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sessionManager = [AFHTTPSessionManager manager];
        sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/xml",@"text/json",@"text/plain",@"text/JavaScript",@"application/json",@"image/jpeg",@"image/png",@"application/octet-stream",nil];
        sessionManager.requestSerializer.timeoutInterval = kBFNetworkingTimeoutInterval;
    });
    return sessionManager;
}

+ (void)requestWithType:(BFHttpRequestType)type urlString:(NSString *)urlString parameters:(NSDictionary *)parameters successBlock:(BFHttpRequestSuccessBlock)successBlock failedBlock:(BFHttpRequestFailedBlock)failedBlock {
    NSString *encodingUrl = [self encodingURLWithString:urlString];
    NSString *absoluteUrl = [self absoluteUrlWithPath:encodingUrl];
    if (type == BFHttpRequestTypeGet) {
        [[self sharedAFManager] GET:absoluteUrl parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            id resultJson = json[@"result"];
            if ([resultJson isKindOfClass:[NSDictionary class]]) {
                successBlock(resultJson);
            }else {
                NSError *error = [NSError errorWithDomain:@"com.vicent" code:-10086 userInfo:@{@"msg":@"数据解析错误"}];
                NSLog(@"数据解析错误");
                failedBlock(error);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (error.code !=-999) {
                if (failedBlock) {
                    failedBlock(error);
                }
            }else{
                NSLog(@"取消队列了");
            }
        }];
    }else if(type == BFHttpRequestTypePost){
        [[self sharedAFManager] POST:absoluteUrl parameters:parameters headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            successBlock(json);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (error.code !=-999) {
                if (failedBlock) {
                    failedBlock(error);
                }
            }else{
                NSLog(@"取消队列了");
            }
        }];
    }
    
}

+ (void)getRequestWithApi:(NSString *)api parameters:(NSDictionary *)parameters successBlock:(void (^)(NSDictionary * _Nonnull))successBlock failedBlock:(void (^)(id _Nonnull))failedBlock {
    [self requestWithType:BFHttpRequestTypeGet urlString:api parameters:parameters successBlock:^(id  _Nonnull responseObject) {
        successBlock(responseObject);
    } failedBlock:^(NSError * _Nonnull error) {
        failedBlock(error);
    }];
}

+ (void)postRequestWithApi:(NSString *)api parameters:(NSDictionary *)parameters successBlock:(void (^)(NSDictionary * _Nonnull))successBlock failedBlock:(void (^)(id _Nonnull))failedBlock {
    [self requestWithType:BFHttpRequestTypePost urlString:api parameters:parameters successBlock:^(id  _Nonnull responseObject) {
        successBlock(responseObject);
    } failedBlock:^(NSError * _Nonnull error) {
        failedBlock(error);
    }];
}


+ (void)downloadRequestWithApi:(NSString *)url
                    param:(NSDictionary *)param
                      progress:(void(^)(NSInteger progress))progress
                  success:(void(^)(NSDictionary *rootDict))success
                  failure:(void(^)(id error))failure {
    NSURLRequest *requset = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    [[self sharedAFManager] downloadTaskWithRequest:requset progress:^(NSProgress * _Nonnull downloadProgress) {
//        progress(downloadProgress.);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
    }];
}


+ (void)cancelDataTasks {
    NSMutableArray *dataTasks = [NSMutableArray arrayWithArray:[self sharedAFManager].dataTasks];
    for (NSURLSessionDataTask *dataTask in dataTasks) {
        [dataTask cancel];
    }
}



@end
